package com.pf.common.utils;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2022/7/9 15:16
 */
@Slf4j
public class DTOUtils {

    /**
     * 实体对象数据转换
     *
     * @param sourceObj   原对象
     * @param targetClazz 目标类型
     * @param <T>
     * @return
     */
    public static <T> T copyToNewObj(Object sourceObj, Class<T> targetClazz) {
        if (sourceObj == null || targetClazz == null) {
            return null;
        }
        try {
            T targetObj = targetClazz.newInstance();
            BeanUtils.copyProperties(sourceObj, targetObj);
            return targetObj;
        } catch (Exception e) {
            log.error("DtoUtils -> copyProperties error", e);
        }
        return null;
    }

    /**
     * 实体对象数据拷贝
     *
     * @param sourceObj
     * @param targetObj
     * @param <T>
     * @return
     */
    public static <T> T copyToObj(Object sourceObj, T targetObj) {
        if (sourceObj == null || targetObj == null) {
            return null;
        }
        try {
            BeanUtils.copyProperties(sourceObj, targetObj);
            return targetObj;
        } catch (Exception e) {
            log.error("DtoUtils -> copyToObj error", e);
        }
        return null;
    }

    /**
     * 集合数据转换为目标类型集合
     *
     * @param sourceList  原集合
     * @param targetClazz 目标类型
     * @param <T>
     * @return
     */
    public static <T> List<T> copyToNewObjList(List<?> sourceList, Class<T> targetClazz) {
        if (sourceList == null || targetClazz == null) {
            return Lists.newArrayList();
        }
        List<T> targetList = Lists.newArrayList();
        sourceList.forEach(sourceObj -> {
            if (sourceObj != null) {
                targetList.add(copyToNewObj(sourceObj, targetClazz));
            }
        });
        return targetList;
    }
}
